/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: WeChatArticleService.java</p>
 *
 * @author zz
 * @date 2024/4/9
 * @version 1.0
 * History:
 * v1.0.0 2024/4/9 Create
 */
package com.haohan.mess.service;

/**
 * <p>Title: WeChatArticleService</p>
 * <p>Description: </p>
 *
 * @author zz
 */

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service
public class WeChatArticleService {

    public static String fetchAndParseArticle(String articleUrl) throws IOException {
        // 使用Jsoup连接到文章URL
        Document doc = Jsoup.connect(articleUrl).get();

        // 提取所有的链接
        Elements links = doc.select("a[href]");

        // 提取所有的图片
        Elements images = doc.select("img[src]");

        // 提取所有的标题
        Elements titles = doc.select("h1, h2, h3, h4, h5, h6");

        for (Element link : links) {
            //System.out.println("链接: " + link.attr("abs:href"));
        }

        for (Element image : images) {
            //System.out.println("图片URL: " + image.attr("abs:src"));
        }

        for (Element title : titles) {
            System.out.println("标题: " + title.text());
        }

        Elements contentElements = doc.select("div#js_content");

        // 处理内容中的图片链接，因为它们可能是相对路径
        contentElements.select("img").forEach(img -> {
            String src = img.absUrl("data-src"); // 微信公众号图片的真实链接在data-src属性中
            System.out.println("图片链接" + src);
            img.attr("src", src);
            img.removeAttr("data-src");
        });

        // 获取处理后的HTML内容
        String contentHtml = contentElements.html();
        //Document document = Jsoup.parse(contentHtml);
        String docInfo = htmlToPlainTextWithParagraphs(contentHtml);
        System.out.println(docInfo);
        //System.out.println("文章内容");
        //System.out.println(document.text());

        // 构建完整的文章信息
        return null;
    }

    private static String htmlToPlainTextWithParagraphs(String html) {
        Document document = Jsoup.parse(html);
        Elements paragraphs = document.select("p");
        StringBuilder textBuilder = new StringBuilder();

        for (Element paragraph : paragraphs) {
            // 如果段落隐藏（如style属性中包含"display: none"），则不包括该段落
            if (!paragraph.attr("style").toLowerCase().contains("display: none")) {
                textBuilder.append(paragraph.text()).append("\n");
            }
        }

        return textBuilder.toString();
    }

    public static void main(String[] args) throws IOException {
        fetchAndParseArticle("https://mp.weixin.qq.com/s/eUYyXj7PKGm61jIsu34GSA");
    }

}

